import Fetch from './fetch'
import { BASE_PATH } from './../config'
import _assign from 'lodash/assign'
/**
 *@description api生成器
 */
export default class ApiGenerator {
  constructor (apiMaps = {}) {
    this.$apis = {}
    this.apisMap = apiMaps
    this.makeApiMap()
    return this.$apis
  }
  makeApiMap () {
    Object.keys(this.apisMap).map(key => {
      this.makeApi(key, this.apisMap[key])
    })
  }
  makeApi (name = '', apis = []) {
    apis.map(api => {
      const apiname = name + '/' + api.name
      const apiDesc = api.desc
      const apiBaseURL = BASE_PATH
      let apiMethod = api.method || 'GET'
      apiMethod = apiMethod.toUpperCase()
      const templateUrl = api.path
      this.assert(api.name, `${templateUrl} :接口name属性不能为空`)
      this.assert(templateUrl.indexOf('/') === 0, `${templateUrl} :接口路径path，首字符应为/`)
      if (apiMethod.toUpperCase() === 'GET') {
        Object.defineProperty(this.$apis, apiname, {
          value (getParams, routeParams) {
            const apiUrl = replaceUrl(templateUrl, routeParams)
            return Fetch(normoalize(_assign({
              url: apiUrl,
              templateUrl: templateUrl,
              baseURL: apiBaseURL,
              method: apiMethod,
              desc: apiDesc
            }), getParams))
          }
        })
      } else {
        Object.defineProperty(this.$apis, apiname, {
          value (getParams, postParams, routeParams) {
            const apiUrl = replaceUrl(templateUrl, routeParams)
            return Fetch(normoalize(_assign({
              url: apiUrl,
              templateUrl: templateUrl,
              baseURL: apiBaseURL,
              method: apiMethod,
              desc: apiDesc
            }), getParams, postParams))
          }
        })
      }
    })
  }

  assert (condition, msg) {
    if (!condition) throw new Error(`[Apior] ${msg}`)
  }
}

function normoalize (options = {}, getData = {}, postData = {}) {
  options.data = postData
  options.params = getData
  return options
}

function replaceUrl (templateUrl = '', routeParams = {}) {
  const regx = /:[0-9a-zA-Z_]+/g
  return templateUrl.replace(regx, mat => {
    for (let item in routeParams) {
      if (item === mat.substr(1)) { return routeParams[item] }
    }
  })
}
